<template>
    <div class="chat-box">
      <!-- 消息列表 -->
      <div class="message-list">
      <div v-for="(message, index) in messages" :key="index" class="message">
        <span>{{ message }}</span>
      </div>
    </div>
  
      <!-- 发送消息表单 -->
      <form>
        <input v-model="newMessage.issue" placeholder="Type your message here...">
        <button @click="sendMessage">发送</button>
      </form>
    </div>


  </template>
  
  <script setup>
import axios from 'axios';
import { onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';

  
  const route = useRoute();
  const userid = '1';

  // 消息列表数据
  const messages = ref([]);

  
  // 新消息输入框的数据
  const newMessage = reactive({
    'issue': '',
  });

  // 回答消息
  var ansMsg = ref()

  const socket = ref(null)

  const initwesockt=()=>{
        socket.value = new WebSocket("ws://localhost:8000/room/user" + userid);
    
        // 当客户端和服务端刚创建好连接(self.accept)之后，自动触发.
        socket.value.onopen =  (event)=>{
            console.log("连接成功")
        }
    
        // 回调函数，客户端接收服务端消息
        socket.value.onmessage =  (event)=>{
            console.log(event.data);

            ansMsg.value = event.data;
            messages.value.push(ansMsg);
        }
  }

    // 发送消息的方法
    function sendMessage() {
    messages.value.push(newMessage.issue);
    let user_input = newMessage.issue;
    
    if (socket.value.readyState === WebSocket.OPEN) {
        console.log('Message sent:', user_input);
        socket.value.send(user_input);
      } else {
        console.error('WebSocket connection is not open');
    }
    // 清空输入框
    newMessage.issue = '';
  }

  onMounted(()=>{
    initwesockt()
  })


  </script>
  
  <style scoped>
  .chat-box {
    display: flex;
    flex-direction: column;
    height: 500px;
    width: 600px;
    border: 1px solid #ccc;
  }
  
  .message-list {
    flex-grow: 1;
    overflow-y: auto;
    padding: 10px;
  }
  
  .message {
    margin-bottom: 10px;
  }
  
  .message span {
    background-color: #f9f9f9;
    padding: 5px 10px;
    border-radius: 5px;
  }
  
  form {
    display: flex;
  }
  
  input {
    flex-grow: 1;
    padding: 5px;
  }
  
  button {
    padding: 5px 10px;
  }

  .chat-momery{
    width: 500px;
    height: 850px;
    background-color: #888;
  }
  </style>